package config

import (
	"github.com/spf13/viper"
	"go-http-server/common/funcs"
	"os"
)

var configFileName = "config"
var configFileType = "yaml"

var ConfigViper *viper.Viper
var Config ConfigStruct

type ConfigStruct struct {
	Version       string
	ServerIp      string
	ServerPort    int
	ServerWWWRoot string
}

func InitConfig() {
	ConfigViper = config()
	Config.ServerIp = ConfigViper.GetString("server.ip")
	Config.ServerPort = ConfigViper.GetInt("server.port")
	Config.ServerWWWRoot = ConfigViper.GetString("server.wwwroot")

	Config.ServerIp = funcs.If(len(Config.ServerIp) > 0, Config.ServerIp, "0.0.0.0").(string)
	Config.ServerPort = funcs.If(Config.ServerPort != 0, Config.ServerPort, 80).(int)
	Config.ServerWWWRoot = funcs.If(len(Config.ServerWWWRoot) > 0, Config.ServerWWWRoot, "www").(string)
}

func config() *viper.Viper {
	path, _ := os.Getwd()
	config := viper.New()
	config.AddConfigPath(path)
	config.SetConfigName(configFileName)
	config.SetConfigType(configFileType)

	if err := config.ReadInConfig(); err != nil {
		panic(err)
	}

	return config
}
